#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <string>

std::vector<int> data;


int save()
{
  pid_t id = fork();
  if(id == 0)
  {
    std::string name = "./backup/";
    name += std::to_string(time(nullptr));
    name += ".backup";

    FILE* fp = fopen(name.c_str(), "w");
    if(fp == nullptr) return 1;

    std::string data_str;
    for(auto d :data)
    {
      data_str += std::to_string(d);
      data_str += " ";
    }

    fputs(data_str.c_str(), fp);

    fclose(fp);
    exit(0);
  }
  else 
  {
    int status;
    pid_t pid = waitpid(id, &status, 0);
    if(pid > 0)
    {
      printf("wait child process success!, exit code: %d\n", WEXITSTATUS(status));
    }
    else 
    {
      printf("wait child process...\n");
    }
  }
  return 0;
}


int main()
{
  int cnt = 0;
  while(true)
  {
    data.push_back(cnt++);
    sleep(1);


    if(cnt % 10 == 0)
    {
      save();
    }
  }

  return 0;
}

